package saleMarket.service;

import saleMarket.dao.LogisticsDao;
import saleMarket.domain.Logistics;
import util.JdbcHelper;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.Collection;

/**
 * @author 张瑞祥
 * @version 1.0  12-07-2020
 */

public class LogisticsService {
    private LogisticsDao logisticsDao = LogisticsDao.getInstance();
    private static LogisticsService logisticsService = new LogisticsService();

    public static LogisticsService getInstance(){return logisticsService;}

    public Logistics find(Integer id)throws SQLException {
        Connection conn = JdbcHelper.getConn();
        conn.setAutoCommit(false);
        Logistics logistics = null;
        try {
            logistics = logisticsDao.find(id,conn);
            conn.commit();
        }catch (SQLException e){
            conn.rollback();
        }finally {
            conn.setAutoCommit(true);
            JdbcHelper.close(conn);
        }
        return logistics;
    }

    public Collection<Logistics> findAll()throws SQLException{
        Connection conn = JdbcHelper.getConn();
        conn.setAutoCommit(false);
        Collection<Logistics> logisticses = null;
        try {
            logisticses = logisticsDao.findAll(conn);
            conn.commit();
        }catch (SQLException e){
            conn.rollback();
        }finally {
            conn.setAutoCommit(true);
            JdbcHelper.close(conn);
        }
        return logisticses;
    }

    public boolean add(Logistics logistics)throws SQLException{
        Connection conn = JdbcHelper.getConn();
        //将自动提交设为false,开始事务
        conn.setAutoCommit(false);
        boolean added = false;
        try {
            added = logisticsDao.add(logistics,conn);
            conn.commit();
        }catch (SQLException e){
            conn.rollback();
        }finally {
            conn.setAutoCommit(true);
            JdbcHelper.close(conn);
        }
        return added;
    }

    public boolean update(Logistics logistics)throws SQLException{
        Connection conn = JdbcHelper.getConn();
        conn.setAutoCommit(false);
        boolean updated = false;
        try {
            updated = logisticsDao.update(logistics,conn);
            conn.commit();
        }catch (SQLException e){
            conn.rollback();
        }finally {
            conn.setAutoCommit(true);
            JdbcHelper.close(conn);
        }
        return updated;
    }

    public boolean delete(Integer id)throws SQLException{
        Connection conn = JdbcHelper.getConn();
        conn.setAutoCommit(false);
        boolean deleted = false;
        try {
            deleted = logisticsDao.delete(id,conn);
            conn.commit();
        }catch (SQLException e){
            conn.rollback();
        }finally {
            conn.setAutoCommit(true);
            JdbcHelper.close(conn);
        }
        return deleted;
    }
}